#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <properties.h>

typedef struct {
    int count;
    char** items;
} list_t;

static void record_prop(const char* key, const char* name, void* opaque) {
    list_t *list = (list_t *) opaque;

    char temp[PROP_VALUE_MAX + PROP_NAME_MAX + 16];
    snprintf(temp, sizeof(temp), "[%s]: [%s]", key, name);
    list->items = realloc(list->items, (list->count + 1) * sizeof(*(list->items)));
    list->items[list->count++] = strdup(temp);
}

static void list_properties(void) {
    list_t list;
    memset(&list, 0, sizeof(list_t));

    /* Record properties in the string list */
    if (property_list(record_prop, &list) < 0)
        return;

    for (int n = 0; n < list.count; n++) {
        printf("%s\n", (char *) list.items[n]);
    }
}

static inline void strncpy_safe(char *dst, size_t dst_size, const char *src) {
    strncpy(dst, src, dst_size);
    dst[dst_size - 1] = 0;
}

int main(int argc, char *argv[]) {
    if (argc == 1) {
        list_properties();
        return 0;
    }

    char value[PROP_VALUE_MAX];
    char default_value[PROP_VALUE_MAX] = {0};
    if (argc > 2) {
        strncpy_safe(default_value, PROP_VALUE_MAX, argv[2]);
    }

    property_get(argv[1], value, default_value);
    printf("%s\n", value);
    return 0;
}
